(function() {

	var b2Vec2 = Box2D.Common.Math.b2Vec2,
		b2AABB = Box2D.Collision.b2AABB,
		b2BodyDef = Box2D.Dynamics.b2BodyDef,
		b2Body = Box2D.Dynamics.b2Body,
		b2FixtureDef = Box2D.Dynamics.b2FixtureDef,
		b2Fixture = Box2D.Dynamics.b2Fixture,
		b2World = Box2D.Dynamics.b2World,
		b2MassData = Box2D.Collision.Shapes.b2MassData,
		b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape,
		b2CircleShape = Box2D.Collision.Shapes.b2CircleShape,
		b2DebugDraw = Box2D.Dynamics.b2DebugDraw,
		b2MouseJointDef = Box2D.Dynamics.Joints.b2MouseJointDef,
		b2RevoluteJointDef = Box2D.Dynamics.Joints.b2RevoluteJointDef,
		b2LineJointDef = Box2D.Dynamics.Joints.b2LineJointDef,
		b2DistanceJointDef = Box2D.Dynamics.Joints.b2DistanceJointDef;


	var itemInfo = [{
			src: 'stone1.png',
			id: 110,
			price: 2300,
			des: '红宝石1'
		}, {
			src: 'stone2.png',
			id: 110,
			price: 2300,
			des: '红宝石2'
		}, {
			src: 'stone4.png',
			id: 110,
			price: 2300,
			des: '红宝石4'
		}, {
			src: 'stone5.png',
			id: 110,
			price: 2300,
			des: '红宝石5'
		}, {
			src: 'stone6.png',
			id: 110,
			price: 2300,
			des: '红宝石6'
		}, {
			src: 'stone7.png',
			id: 110,
			price: 2300,
			des: '红宝石7'
		}, {
			src: 'stone8.png',
			id: 110,
			price: 2300,
			des: '红宝石8'
		}, {
			src: 'stone9.png',
			id: 110,
			price: 2300,
			des: '红宝石9'
		}, {
			src: 'stone10.png',
			id: 110,
			price: 2300,
			des: '红宝石10'
		}, {
			src: 'stone11.png',
			id: 110,
			price: 2300,
			des: '红宝石11'
		}, {
			src: 'stone12.png',
			id: 110,
			price: 2300,
			des: '红宝石12'
		}, {
			src: 'stone13.png',
			id: 110,
			price: 2300,
			des: '红宝石13'
		}, {
			src: 'stone14.png',
			id: 110,
			price: 2300,
			des: '红宝石14'
		}, {
			src: 'stone15.png',
			id: 110,
			price: 2300,
			des: '红宝石15'
		}, {
			src: 'stone16.png',
			id: 110,
			price: 2300,
			des: '红宝石16'
		}, {
			src: 'stone17.png',
			id: 110,
			price: 2300,
			des: '红宝石17'
		}, {
			src: 'stone18.png',
			id: 110,
			price: 2300,
			des: '红宝石18'
		}, {
			src: 'stone19.png',
			id: 110,
			price: 2300,
			des: '红宝石19'
		}, {
			src: 'stone20.png',
			id: 110,
			price: 2300,
			des: '红宝石20'
		}, {
			src: 'stone21.png',
			id: 110,
			price: 2300,
			des: '红宝石21'
		}, {
			src: 'stone22.png',
			id: 110,
			price: 2300,
			des: '红宝石22'
		}, {
			src: 'stone23.png',
			id: 110,
			price: 2300,
			des: '红宝石23'
		}, {
			src: 'stone24.png',
			id: 110,
			price: 2300,
			des: '红宝石24'
		}, {
			src: 'stone25.png',
			id: 110,
			price: 2300,
			des: '红宝石25'
		}]
		// 配置文件
	var _conf = {
		debug: 0,

		worldScale: 30,
		g: 9,

		// 珠子的属性 密度 摩擦力 损耗
		_d: 2,
		_f: 0.1,
		_r: 0.1,
		itemLen: itemInfo.length,
		maxLen: 21,

		// 珠子限速
		maxV: 3
	}

	var result = [];
	var _step = [];

	var canvas = document.getElementById("canvas");
	var context = canvas.getContext("2d");

	var world = new b2World(new b2Vec2(0, _conf.g), false);

	var RAF = (function(callback) {
		return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) {
			window.setTimeout(callback, 1000 / 60);
		};
	})();

	(function debugDraw() {
		var _debugDraw = new b2DebugDraw();
		_debugDraw.SetSprite(document.getElementById("canvas").getContext("2d"));
		_debugDraw.SetDrawScale(30.0);
		_debugDraw.SetFillAlpha(0.0);
		_debugDraw.SetLineThickness(0.8);

		_debugDraw.SetFlags(b2DebugDraw.e_shapeBit);
		world.SetDebugDraw(_debugDraw);
	})();

	var global_fixDef = new b2FixtureDef;
	global_fixDef.density = _conf._d;
	global_fixDef.friction = _conf._f;
	global_fixDef.restitution = _conf._r;

	var _necklace;

	// TOOD 修改项链
	function changeNecklace(opt) {

		var bodyDef = new b2BodyDef;

		bodyDef.type = b2Body.b2_staticBody;
		global_fixDef.shape = new b2CircleShape(200 / _conf.worldScale);

		bodyDef.userData = null;
		bodyDef.position.Set(canvas.width / 2 / _conf.worldScale, 250 / _conf.worldScale);

		_necklace = world.CreateBody(bodyDef);
		_necklace.CreateFixture(global_fixDef);
	}

	// TODO 创建珠子
	function createPearl(opt) {

		var bodyDef = new b2BodyDef;
		bodyDef.type = b2Body.b2_dynamicBody;
		bodyDef.linerDamping = 1;

		// 随机从链子左右侧下落
		var _dx = Math.random() > 0.5 ? 1 : -1;

		bodyDef.position.Set((canvas.width / 2 + _dx) / _conf.worldScale, 50 / _conf.worldScale);

		bodyDef.userData = opt;
		bodyDef.userData.dirct = _dx == 1 ? 'right' : 'left';
		bodyDef.userData.img = new Image();
		bodyDef.userData.img.src = opt.src;

		global_fixDef.shape = new b2CircleShape(opt.r / _conf.worldScale);

		var body = world.CreateBody(bodyDef);
		body.CreateFixture(global_fixDef);

		// body.ApplyImpulse(new b2Vec2(10 / 30, 0), body.GetWorldCenter());

		var _joint = new b2RevoluteJointDef();
		var anchor = new b2Vec2(canvas.width / 2 / _conf.worldScale, 250 / _conf.worldScale);
		_joint.Initialize(body, _necklace, anchor);
		// _joint.dampingRaio = 1;

		world.CreateJoint(_joint);

		_step.push(body);
		2
	}

	// TODO 创建吊坠
	function createPendant(opt) {

		var bodyDef = new b2BodyDef;
		bodyDef.type = b2Body.b2_dynamicBody;
		// bodyDef.linerDamping = 1;
		// bodyDef.angularDamping = 1;

		var x = canvas.width / 2 / _conf.worldScale,
			y = 450 / _conf.worldScale + opt.r / _conf.worldScale;

		bodyDef.position.Set(x, y);

		bodyDef.userData = opt;
		bodyDef.userData.img = new Image();
		bodyDef.userData.img.src = opt.src;

		global_fixDef.shape = new b2CircleShape(opt.r / _conf.worldScale);

		var body = world.CreateBody(bodyDef);
		body.CreateFixture(global_fixDef);


		var _joint = new b2RevoluteJointDef();
		var anchor = new b2Vec2(canvas.width / 2 / _conf.worldScale, 450 / _conf.worldScale);
		_joint.Initialize(body, _necklace, anchor);
		// _joint.dampingRaio = 1;

		world.CreateJoint(_joint);


		// 给力
		body.ApplyImpulse(new b2Vec2(100 / 30, 0), body.GetWorldCenter());
	}

	// 根据重力重新设置珠子动向
	function applyItems(a, b, g) {
		// for (var b = world.m_bodyList; b != null; b = b.m_next) {
		// 	if (b.GetUserData() && b.GetUserData().type === 'pearl') {
		// 		b.ApplyImpulse(new b2Vec2(b / 30, g/30), b.GetWorldCenter());
		// 	}
		// }



		if (b === 0 && g === 0) {
			x = 0;
			y = 9;
		} else {
			if (Math.abs(b) >= Math.abs(g)) {
				y = b > 0 ? 9 : -9;
				x = y * g / b;
			} else {
				x = g > 0 ? 9 : -9;
				y = x * b / g;
			}
		}

		// console.log(x, y, g, b);

		world && world.SetGravity(new b2Vec2(x, y));
	}

	function main() {

		changeNecklace();

		(function loop() {
			world.Step(1 / 60, 10, 10);

			context.clearRect(0, 0, canvas.width, canvas.height);
			if (_conf.debug) {
				world.DrawDebugData();
			}

			context.beginPath();

			world.ClearForces();

			for (var b = world.m_bodyList; b != null; b = b.m_next) {
				if (b.GetUserData() && b.GetUserData().type === 'pearl') {
					// b.WakeUp();

					var lv = b.GetLinearVelocity()
					var _vx = Math.min(lv.x, _conf.maxV);
					var _vy = Math.min(lv.y, _conf.maxV);

					b.SetLinearVelocity(new b2Vec2(_vx, _vy));

					// console.log(b.GetLinearVelocity());
					var data = b.GetUserData();
					context.save();

					// debugger;
					context.translate(b.GetPosition().x * _conf.worldScale, b.GetPosition().y * _conf.worldScale);
					context.rotate(b.GetAngle());

					// draw image
					context.drawImage(data.img, 0, 0, data.img.width, data.img.height, -data.r, -data.r, data.r * 2, data.r * 2);
					context.restore();

				}
			}

			RAF(loop);

		})();
	}

	var cur_ballIdx = 0;
	// 显示珠子详情
	function showBallDetail(idx) {
		idx = idx % (idx > 0 ? _conf.itemLen : -_conf.itemLen);

		var ballIdx = idx > 0 ? _conf.itemLen - idx : -1 * idx;
		if (ballIdx === cur_ballIdx) return;

		cur_ballIdx = ballIdx;

		var ballDetail = itemInfo[ballIdx];

		// console.log(ballDetail);

		$el.src.attr('src', "images/stone/" + ballDetail['src']);
		$el.des.html(ballDetail['des']);
		$el.price.html(ballDetail['price'])
	}

	var $el = {
		cvs: $("#canvas"),
		cvs_wrap : $("#cvs_wrap"),
		index_page: $("#index"),
		index_btn: $("#start"),

		custom_page: $("#custom"),
		item_list: $("#item_list"),
		items: [],

		btn_new: $("#new"),
		btn_edit: $("#edit"),
		btn_share: $("#share"),
		btn_undo: $("#undo"),

		detail: $("#detail"),
		des: $("#detail_name"),
		price: $("#detail_price"),
		src: $("#detail_src")
	}

	var winH = window.innerHeight;
	var winW = window.innerWidth;

	var _origin = {
		x: winW / 2,
		y: winH
	}

	var p1 = {},
		p2 = {},
		last_ang = 0,
		cur_ang;
	var isTouch = false,
		isCreate = false;

	function start() {

		initItems();

		main();

		initEvent();
	}

	function initEvent() {
		// init event
		$el.index_btn.on('click', function() {
			$el.index_page.hide();
			$el.custom_page.show();
			main();
		});

		$el.item_list.on('touchstart', function(e) {
			console.log('touch start!');
			var data = e.originalEvent.changedTouches[0];

			p1.x = data.pageX;
			p1.y = data.pageY;

			isTouch = true;
			isCreate = true;
			e.preventDefault();
			e.stopPropagation();
		});

		$el.item_list.on('touchmove', function(e) {

			if (!isTouch) return;

			var data = e.originalEvent.changedTouches[0];

			p2.x = data.pageX;
			p2.y = data.pageY;

			var dx2 = p2.x - _origin.x;
			var dy2 = p2.y - _origin.y;
			var dx1 = p1.x - _origin.x;
			var dy1 = p1.y - _origin.y;

			var a1 = Math.atan(dy1 / dx1);
			var a2 = Math.atan(dy2 / dx2);

			if ((a1 < 0 && a2 < 0) || (a1 > 0 && a2 > 0)) {
				cur_ang = last_ang + (a2 - a1) * 180 / 3;
			} else {
				cur_ang = last_ang + (Math.PI - Math.abs(a1) - Math.abs(a2)) * 180 / 3 * (a2 > 0 ? -1 : 1);
			}

			var da = 360 / _conf.itemLen;
			var idx = Math.round(cur_ang / da);
			showBallDetail(idx);
			cur_ang = idx * da;

			// console.log(cur_ang);

			$el.item_list.css({
				'transform': 'rotate(' + cur_ang + 'deg)',
				'-webkit-transform': 'rotate(' + cur_ang + 'deg)'
			});

			isCreate = false;
			e.preventDefault();
			e.stopPropagation();
		});

		$el.item_list.on('touchend', function(e) {
			last_ang = cur_ang || 0;
			isTouch = false;
			e.preventDefault();
			e.stopPropagation();
		});

		$el.item_list.on('touchend', 'li', function(e) {
			return;
			if (!isCreate) return;
			var type = $(this).data('type'),
				idx = parseInt($(this).data('idx'));

			var src = itemInfo[idx].src;

			if (_conf.maxLen <= result.length) {
				return;
			}

			result.push(itemInfo[idx]);

			// 创建珠子
			createPearl({
				type: type,
				r: 30,
				src: 'images/stone/' + src
			});
		});

		$("#detail").on('touchend', function() {
			// console.log(cur_ballIdx);
			var type = $(this).data('type') || 'pearl';

			var src = itemInfo[cur_ballIdx].src;

			if (_conf.maxLen <= result.length) {
				return;
			}

			result.push(itemInfo[cur_ballIdx]);

			// 创建珠子
			createPearl({
				type: type,
				r: 30,
				src: 'images/stone/' + src
			});
		});

		var scale = 1;
		$("#big").on('touchend', function() {

			scale += 0.1;

			scale = Math.min(scale, 2);

			var css = {
				'transform': 'scale(' + scale + ',' + scale + ')',
				'-webkit-transform': 'scale(' + scale + ',' + scale + ')'
			};

			$el.cvs_wrap.css(css);

			e.preventDefault();
			e.stopPropagation();


		});

		$("#sml").on('touchend', function() {
			scale -= 0.1;
			scale = Math.max(scale, 0.5);

			var css = {
				'transform': 'scale(' + scale + ',' + scale + ')',
				'-webkit-transform': 'scale(' + scale + ',' + scale + ')'
			};

			$el.cvs_wrap.css(css);

			e.preventDefault();
			e.stopPropagation();

		});


		// new 
		$el.btn_new.on('touchend', function() {
			console.log('new');

			result.length = 0;
			_step.length = 0;

			for (var b = world.m_bodyList; b != null; b = b.m_next) {
				if (b.GetUserData() && b.GetUserData().type === 'pearl') {
					world.DestroyBody(b);
				}
			}

			e.preventDefault();
			e.stopPropagation();


		});

		// edit 
		$el.btn_edit.on('touchstart', function() {
			console.log('edit');
			e.preventDefault();
			e.stopPropagation();

		});

		// share
		$el.btn_share.on('touchstart', function() {
			console.log('share');
			alert('调用分享接口')
			e.preventDefault();
			e.stopPropagation();

		});

		// undo 
		$el.btn_undo.on('touchstart', function() {
			console.log('undo');

			var body = _step.pop();
			if (body) {
				world.DestroyBody(body);
			};
		});

		// 移动canvas
		var cvs_sp = {};
		var cvs_l = 0;
		var cvs_t = 0;
		var cvs_dx ,cvs_dy;
		$("#cvs_wrap").on('touchstart', function(e) {
			var data = e.originalEvent.changedTouches[0];
			cvs_sp.x = data.pageX;
			cvs_sp.y = data.pageY;

			e.preventDefault();
			e.stopPropagation();

		});

		$("#cvs_wrap").on('touchmove', function(e) {
			var data = e.originalEvent.changedTouches[0];
			cvs_dx = data.pageX - cvs_sp.x;
			cvs_dy = data.pageY - cvs_sp.y;

			$(this).css({
				left : cvs_l + cvs_dx,
				top : cvs_t + cvs_dy
			});

			e.preventDefault();
			e.stopPropagation();

		});

		$("#cvs_wrap").on('touchend', function(e) {
			cvs_l += cvs_dx;
			cvs_t += cvs_dy;
			// var data = e.originalEvent.changedTouches[0];
			// cvs_sp.x = data.pageX;
			// cvs_sp.y = data.pageY;
		});

	}

	function initItems() {
		var len = itemInfo.length;
		var r = 250;
		var ang = Math.PI * 2 / len;
		var x, y;
		var items = '';

		for (var i = 0; i < len; i++) {
			x = r * Math.sin(ang * i) + r
			y = r - r * Math.cos(ang * i);

			items += "<li data-type='pearl' data-idx='" + i + "' style='left:" + x + "px ; top : " + y + "px '><img src='images/stone/" + itemInfo[i].src + "' /></li>";
		}

		$el.item_list.append(items);
	}

	window.addEventListener("deviceorientation", function(e) {
		// 处理event.alpha、event.beta及event.gamma
		var gamma = parseInt(e.gamma),
			beta = parseInt(e.beta),
			alpha = parseInt(e.alpha);
		// $("#gam").html('g:' + gamma);
		// $("#bet").html('b:' + beta);
		// $("#alp").html("a:" + alpha)

		applyItems(alpha, beta, gamma);

	}, true);


	start();
})();